package pl.mdziedzic.unittests;


import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.junit.*;



import static org.junit.Assert.*;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class bananaScrumAddItem {
	private static WebDriver driver;
	private static String baseUrl;
	private Integer num;

	private static final String login="admin";
	private static final String pass="password";

	@BeforeClass
	public static void setUp() throws Exception {
		driver = new FirefoxDriver();
		baseUrl = "http://demo.bananascrum.com/login/";
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	@Test
	public void testSelenGolf1() throws Exception {
		driver.get(baseUrl);
		driver.findElement(By.name("login")).click();
		driver.findElement(By.name("login")).clear();
		driver.findElement(By.name("login")).sendKeys(login);
		driver.findElement(By.name("password")).click();
		driver.findElement(By.name("password")).clear();
		driver.findElement(By.name("password")).sendKeys(pass);

		driver.findElement(By.name("commit")).click();

		setProject("Project Moon");
		num = new Random().nextInt(1000);
		addBacklogItem();
		for (int second = 0;; second++) {
			if (second >= 15) fail("timeout");
			try { 
				if (driver.getPageSource().contains("MyStory_"+num)) break; 
			} 
			catch (Exception e) {
					
			}
			Thread.sleep(1000);
		}		
		assertTrue(driver.getPageSource().contains("MyStory_"+num));
	}

	@AfterClass
	public static void tearDown() throws Exception {
		driver.quit();
	}

	public void setProject(String pName) {
		WebElement e = driver.findElement(By.id("project_id"));
		Select s = new Select(e);
		s.selectByVisibleText(pName);
	}
	
	public void addBacklogItem() {
		driver.findElement(By.className("backlog")).click();
		driver.findElement(By.className("new-backlog-item-button")).click();
		driver.findElement(By.id("item_user_story")).click();
		driver.findElement(By.id("item_user_story")).sendKeys("MyStory_"+num);
		driver.findElement(By.id("item_description")).click();
		driver.findElement(By.id("item_description")).sendKeys("Opis MyStory_"+num);
		
		WebElement e = driver.findElement(By.id("item_estimate"));
		Select s = new Select(e);
		s.selectByVisibleText("13");
		
		driver.findElement(By.name("commit")).click();
		
	}
	
	
	private boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}

}
